﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using CloudShot.Utils;
using CloudShot.Utils.Encoding;

namespace CloudShot
{
	public partial class RecordProcessingForm : Form
	{
		private readonly int _fps;
		private readonly BackgroundWorker _worker = new BackgroundWorker();
		private readonly List<Image> _images;

		public Image Image { get; private set; }

		public RecordProcessingForm(IEnumerable<Image> images, int fps)
		{
			_fps = fps;
			InitializeComponent();
			_images = images.ToList();
		}

		#region Event Handlers

		private void OnLoad(object sender, EventArgs e)
		{
			_worker.WorkerReportsProgress = true;
			_worker.WorkerSupportsCancellation = true;
			_worker.DoWork += OnGifCreating;
			_worker.ProgressChanged += OnGifCreatingProgressChanged;
			_worker.RunWorkerCompleted += OnGifCreated;

			progressProcessing.Minimum = 0;
			progressProcessing.Maximum = _images.Count;
			progressProcessing.Visible = true;

			_worker.RunWorkerAsync();
		}

		private void OnCancelClick(object sender, EventArgs e)
		{
			if (_worker.IsBusy)
				_worker.CancelAsync();
		}

		#endregion

		#region Async Works

		private void OnGifCreating(object sender, DoWorkEventArgs e)
		{
			Image image = _images.FirstOrDefault();

			if (image == null)
			{
				e.Cancel = true;
				return;
			}

			var encoder = new AnimatedGifEncoder();
			//encoder.SetQuality(1); //1 - maximum quality, 20 - min quality
			//encoder.SetDispose(3);
			//encoder.SetTransparent(Color.White);

			//encoder.SetRepeat(cbLoop.Checked ? 0 : -1); //if checked, 0 else -1
			encoder.SetRepeat(0); //if checked, 0 else -1

			encoder.SetSize(image.Width, image.Height);
			encoder.SetFrameRate(_fps);
			//encoder.SetDelay(CAPTURE_INTERVAL);

			encoder.Start();

			for (int i = 0; i < _images.Count; i++)
			{
				encoder.AddFrame(_images[i]);
				_worker.ReportProgress(i);

				if (_worker.CancellationPending)
				{
					e.Cancel = true;
					return;
				}
			}

			e.Result = encoder.Finish();
		}

		private void OnGifCreatingProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			progressProcessing.Value = e.ProgressPercentage;
		}

		private void OnGifCreated(object sender, RunWorkerCompletedEventArgs e)
		{
			if (e.Error != null)
			{
				ErrorsHelper.TraceError(e.Error);
				DialogResult = DialogResult.Cancel;
				return;
			}

			if (e.Cancelled)
			{
				DialogResult = DialogResult.Cancel;
				return;
			}

			Image = e.Result as Image;
			progressProcessing.Visible = false;
			DialogResult = DialogResult.OK;
		}

		#endregion
	}
}
